package com.dg11185.nearshop.activity.welcome;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nearshop.R;
import com.dg11185.nearshop.activity.home.HomeFragment2;
import com.dg11185.nearshop.activity.setting.SettingFragment;
import com.dg11185.nearshop.activity.shop.ShopFragment;
import com.dg11185.nearshop.activity.user.UserFragment;
import com.dg11185.nearshop.app.Constants;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.message.PushAgent;
import com.umeng.update.UmengUpdateAgent;

public class MainTabActivity extends FragmentActivity {

    public static FragmentTabHost mTabHost;

    private LayoutInflater layoutInflater;

    private static boolean isHintUpate = false;

    private PushAgent mPushAgent;// 消息推送组件
    private FeedbackAgent mFeedbackAgent;// 用户反馈组件

    // 替换其他的Fragment修改这里的代码

    private Class fragmentArray[] = { HomeFragment2.class, ShopFragment.class,
            UserFragment.class, SettingFragment.class };

    private int mImageViewArray[] = { R.drawable.main_tab_home_btn,
            R.drawable.main_tab_shop_btn, R.drawable.main_tab_user_btn,
            R.drawable.main_tab_more_btn };

    private String mTextviewArray[] = { "首页", "商家", "我的", "更多" };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_layout);
        initView();
        initUmeng();
    }

    private void initUmeng() {
        // 统计分析
        // MobclickAgent.setSessionContinueMillis(3000);
        MobclickAgent.openActivityDurationTrack(false);
        // MobclickAgent.updateOnlineConfig(this);
        // MobclickAgent.setDebugMode(true);
        // 消息推送
        mPushAgent = PushAgent.getInstance(this);
        SharedPreferences preferences = getSharedPreferences(
                Constants.preferences_system_setting, Context.MODE_PRIVATE);
        if (preferences.getBoolean(Constants.is_get_push_news, true)) {
            mPushAgent.enable();
        } else {
            mPushAgent.disable();
        }
        // 自动更新
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        if (!isHintUpate) {
            UmengUpdateAgent.setUpdateOnlyWifi(false);
            UmengUpdateAgent.update(this);            
            isHintUpate = true;
        }
        // 用户反馈
        if (mFeedbackAgent == null) {
            mFeedbackAgent = new FeedbackAgent(this);
            mFeedbackAgent.sync();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        int currentIndex = getIntent().getIntExtra("current_index", -1);
        if (currentIndex != -1) {
            mTabHost.setCurrentTab(currentIndex);
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initView() {
        layoutInflater = LayoutInflater.from(this);

        mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
            TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
                    .setIndicator(getTabItemView(i));
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
        }
    }

    // 可以随时将每个Item替换成自定义的layout，灵活性比RadioGroup更大
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.main_tab_item_view, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.main_tab_icon);
        imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.main_tab_txt);
        textView.setText(mTextviewArray[index]);

        return view;
    }

    private static Boolean isQuit = false;

    private Timer timer = new Timer();

    private void onBack() {
        if (isQuit == false) {
            isQuit = true;
            Toast.makeText(getBaseContext(), "再按一次退出常惠摇摇", Toast.LENGTH_SHORT)
                    .show();
            TimerTask task = null;
            task = new TimerTask() {
                @Override
                public void run() {
                    isQuit = false;
                }
            };
            timer.schedule(task, 2000);
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (!hideDropWindow())
            onBack();
    }

    private boolean hideDropWindow() {

        Fragment f = this.getSupportFragmentManager().findFragmentByTag(
                mTextviewArray[mTabHost.getCurrentTab()]);

        /**
         * 如果在某个Fragment中有使用到@{link}com.wlper.view.ExpandableTab 控件，
         * 要在此作隐藏下拉窗口的操作
         */
        if ((f instanceof ShopFragment))
            return ((ShopFragment) f).hideDropWindow();
        if ((f instanceof HomeFragment2))
            return ((HomeFragment2) f).hideDropWindow();
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                // 如果隐藏下拉窗口成功的话，就不把Touch事件传递给下层的控件了
                if (hideDropWindow()) {
                    return true;
                }
        }
        return super.dispatchTouchEvent(ev);
    }

}
